package com.qf.openapi.web.master.service.impl;

import cn.hutool.core.io.file.FileAppender;
import cn.hutool.crypto.digest.DigestUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qf.openapi.web.master.dao.UserDao;
import com.qf.openapi.web.master.entity.User;
import com.qf.openapi.web.master.service.UserSevice;
import com.qf.openapi.web.master.utils.FileAppendUtils;
import com.qf.openapi.web.master.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import sun.text.resources.FormatData;

import javax.servlet.http.HttpServletRequest;
import java.beans.Beans;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@Service
@Slf4j
public class UserSeviceImpl implements UserSevice {

	@Autowired
	private UserDao userDao;

	@Autowired
	private FileAppendUtils<User> fileAppenderUtils;

	@Transactional(propagation=Propagation.SUPPORTS)
	@Override
	public User getUser( Integer id ) {

		return userDao.getUserById( id );

	}

	@Override
	public Integer deleteUserByName( String name ) {

		Integer integer=userDao.deleteUserByName( name );
		return integer;
	}


	/*
	 * 添加用户
	 * */
	@Override
	public Integer add( String realPath,AddFormData addformData ) throws IOException {
		MultipartFile source=addformData.getSource( );


		//生成一个随机的文件名
		String fileName=UUID.randomUUID( ).toString( ).substring( 0,6 );
		//获取上传的文件名
		String originalFilename=source.getOriginalFilename( );
		//获取文件扩展名
		String extension=FilenameUtils.getExtension( originalFilename );

		String filename=fileName+"."+extension;

		User user=new User( );
		//使用工具类来对bean复制
		BeanUtils.copyProperties( addformData,user );

		//使用工具类加密
		String s=DigestUtil.md5Hex( addformData.getPassword( ) );
		user.setPassword( s );
		user.setImg( filename );
		Integer integer=insertUser( user );
		log.info( "插入的用户信息",user );


		//表单中的文件处理
		File file=new File( realPath );

		//判断目录是否存在，不存在就创建
		if(!file.exists( )) {
			file.mkdirs( );
		}

		source.transferTo( new File( realPath+File.separator+filename ) );

		log.info( "注册成功" );

		return integer;
	}

	@Override
	@Transactional(rollbackFor=Exception.class)
	public Result deleteUsers( int[] arr ) {

		Integer integer=userDao.deleteUsers( arr );
		if(integer>0) {
			return new Result( ResultVo.SUCCESS,"Delete,Successful!!!" );
		}
		return new Result( ResultVo.UNSUCCESS,"Delete,Unsuccessful!!!" );
	}

	@Override
	public Integer updateById( String realPath,AddFormData addformData ) throws IOException {
		MultipartFile source=addformData.getSource( );


		//生成一个随机的文件名
		String fileName=UUID.randomUUID( ).toString( ).substring( 0,6 );
		//获取上传的文件名
		String originalFilename=source.getOriginalFilename( );
		//获取文件扩展名
		String extension=FilenameUtils.getExtension( originalFilename );

		String filename=fileName+"."+extension;

		User user=new User( );
		//使用工具类来对bean复制
		BeanUtils.copyProperties( addformData,user );

		//使用工具类加密
		String s=DigestUtil.md5Hex( addformData.getPassword( ) );
		user.setPassword( s );
		user.setImg( filename );
		Integer integer=userDao.updateUser( user );
		log.info( "插入的用户信息",user );


		//表单中的文件处理
		File file=new File( realPath );

		//判断目录是否存在，不存在就创建
		if(!file.exists( )) {
			file.mkdirs( );
		}

		source.transferTo( new File( realPath+File.separator+filename ) );

		log.info( "修改成功" );

		return integer;

	}

	@Override
	public TableVo< User > getUsersByContdition( Integer page,Integer limit,UserVo userVo ) {
		PageHelper.startPage( page,limit );
		List< User > list=userDao.getUsersByContdition( userVo );
		PageInfo< User > userPageInfo=new PageInfo<>( list );
		int total=(int) userPageInfo.getTotal( );
		TableVo< User > tableVo=new TableVo< User >( 0,"Success",total,list );
		return tableVo;
	}

	@Override
	public String export( ) throws IOException, IllegalAccessException, ClassNotFoundException {

		//生成一个文件追加器
		int page=1;
		String realpath=ResultVo.RealPath;
		String name=UUID.randomUUID( ).toString( ).substring( 0,7 )+".csv";
		File file=new File( realpath );
		if(!file.exists( )) {
			file.mkdirs( );
		}
		File finallyFile=new File( realpath+File.separator+name );
		FileAppender fileAppender=new FileAppender( finallyFile,16,true );

		PageHelper.startPage( page,500 );
		List< User > allUser=userDao.getAllUser( );
		PageInfo< User > userPageInfo=new PageInfo<>( allUser );

		//调用工具类来实现
		fileAppenderUtils.getHead( fileAppender ,User.class.getCanonicalName());
		fileAppenderUtils.fileAppend( allUser,fileAppender ,User.class.getCanonicalName());
		long total=userPageInfo.getTotal( );

		//使用工具类的批量追加
		while(allUser.size()>0) {
			++page;
			PageHelper.startPage( page,500 );
			allUser=userDao.getAllUser( );
			userPageInfo=new PageInfo<>( allUser );
			total=userPageInfo.getTotal( );
			if(allUser.size()>0){
				fileAppenderUtils.fileAppend( allUser,fileAppender,User.class.getCanonicalName());
			}else {
				break;
			}
		}

		return name;
	}

	@Override
	public User login( String username,String password ) {
		log.debug( "userservice查询用户收到的参数为username={},passowrd={}",username,password );

		//工具类将传入的密码转化为加密的密码来核对
		String s=DigestUtil.md5Hex( password );
		User user=userDao.getUserByNameAndPassword( username,s );
		return user;
	}

	@Override
	public User selectByName( String username ) {
		User userByName=userDao.getUserByName( username );
		return userByName;
	}

	@Override
	public Integer insertUser( User user ) {
		Integer integer=userDao.insertUser( user );
		return integer;
	}

	@Override
	@Transactional(rollbackFor=Exception.class)
	public Integer register( String realPath,FormData formData ) throws IOException {
		MultipartFile source=formData.getSource( );


		//生成一个随机的文件名
		String fileName=UUID.randomUUID( ).toString( ).substring( 0,6 );
		//获取上传的文件名
		String originalFilename=source.getOriginalFilename( );
		//获取文件扩展名
		String extension=FilenameUtils.getExtension( originalFilename );

		String filename=fileName+"."+extension;

		User user=new User( );
		//使用工具类来对bean复制
		BeanUtils.copyProperties( formData,user );

		//使用工具类加密
		String s=DigestUtil.md5Hex( formData.getPassword( ) );
		user.setPassword( s );
		user.setImg( filename );
		Integer integer=insertUser( user );
		log.info( "插入的用户信息",user );


		//表单中的文件处理
		File file=new File( realPath );

		//判断目录是否存在，不存在就创建
		if(!file.exists( )) {
			file.mkdirs( );
		}

		source.transferTo( new File( realPath+File.separator+filename ) );

		log.info( "注册成功" );

		return integer;
	}

	@Override
	public TableVo< User > getUsers( Integer page,Integer limit ) {
		Integer count=userDao.getCount( );

		PageHelper.startPage( page,limit );
		List< User > data=userDao.getAllUser( );
		TableVo tableVo=new TableVo( 0,"查询成功",count,data );
		return tableVo;
	}
}
